import sys

from PySide6.QtCore import QSortFilterProxyModel, QDate, QTimer
from PySide6.QtGui import QStandardItemModel, QShortcut, QKeySequence
from PySide6.QtWidgets import QFrame, QApplication, QAbstractItemView, QHeaderView, QMessageBox

from backend.db.database import SessionLocal
from backend.services.consumption_services import ConsumptionService
from front.models.consumption_list_model import ConsumptionModel, RefundButtonDelegate
from front.ui.ui_consump_list import Ui_Frame


class ConsumptionList(QFrame, Ui_Frame):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.end_date = None
        self.start_date = None
        self.proxy_model = None
        self.model = None
        self.setupUi(self)
        self.start_dateEdit.setDate(QDate.currentDate().addDays(-3))
        self.end_dateEdit.setDate(QDate.currentDate())
        self.start_dateEdit.dateChanged.connect(lambda: QTimer.singleShot(0, self.check_dateEdit))
        self.end_dateEdit.dateChanged.connect(lambda: QTimer.singleShot(0, self.check_dateEdit))

    def set_table_view(self, data):
        data = [i.model_dump() for i in data]
        if self.proxy_model:
            self.proxy_model.deleteLater()  # 释放代理模型资源
            self.proxy_model = None
        if self.model:
            self.model.deleteLater()  # 释放源模型资源
            self.model = None
        self.model = ConsumptionModel(data)
        self.proxy_model = QSortFilterProxyModel()
        self.proxy_model.setSourceModel(self.model)
        self.tableView.setModel(self.proxy_model)
        self.tableView.setSortingEnabled(True)
        self.tableView.resizeColumnsToContents()
        header = self.tableView.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.Stretch)
        header.setSectionResizeMode(5, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(6, QHeaderView.ResizeToContents)
        header.setSectionResizeMode(7, QHeaderView.ResizeToContents)
        self.connect_refund(self.show_refund_message)

    def connect_refund(self, callback_func):
        delegate = RefundButtonDelegate(self)
        delegate.consume_callback = callback_func
        self.tableView.setItemDelegateForColumn(9, delegate)

    def search_consumption_information(self, start_time=None, end_time=None, value=None):
        """搜索消费信息"""
        with SessionLocal() as session:
            consumption_service = ConsumptionService(session)
            a = consumption_service.get_designate_consumption(start_time, end_time, value)
            self.set_table_view(a)

    def show_refund_message(self, row):
        """添加退款记录"""
        reply = QMessageBox.question(
            self,
            "确认退款",
            "是否确认退款？此操作不可撤销。",
            QMessageBox.Yes | QMessageBox.No,  # 显示"是"和"否"按钮
            QMessageBox.No  # 默认选中"否"按钮
        )
        if reply == QMessageBox.Yes:
            model = self.proxy_model
            if model is None:
                return
            user_id = model.index(row, 1).data()
            consumption_id = model.index(row, 0).data()
            amount = model.index(row, 4).data()
            answer = {'member_id': user_id, 'transaction_id': consumption_id, "amount": amount}
            with SessionLocal() as session:
                consumption_service = ConsumptionService(session)
                consumption_item = consumption_service.add_refund(**answer)
                self.search_consumption_information()

    def check_dateEdit(self):
        """获取日期
        根据是否选中
        """
        print("【DEBUG】check_dateEdit 被调用了！")
        self.start_date = None
        self.end_date = None
        start_date = self.start_dateEdit.date()
        end_date = self.end_dateEdit.date()

        if start_date.isValid() and end_date.isValid():
            if start_date > end_date:
                self.start_dateEdit.blockSignals(True)
                self.end_dateEdit.blockSignals(True)
                self.end_dateEdit.setDate(QDate.currentDate())
                self.start_dateEdit.setDate(QDate.currentDate().addDays(-3))
                self.start_dateEdit.blockSignals(False)
                self.end_dateEdit.blockSignals(False)
                QMessageBox.warning(self, "警告", "结束时间不能早于开始时间！")
                return
        if start_date.isValid():
            self.start_date = start_date.toPython()
        if end_date.isValid():
            self.end_date = end_date.toPython()
        self.consumption_to_tableview_time()

    def consumption_to_tableview_time(self):
        """填充consumption到table_view,包含时间"""
        with SessionLocal() as session:

            consumption_service = ConsumptionService(session)
            consumption_item = consumption_service.get_designate_consumption(start_date=self.start_date,
                                                                             end_date=self.end_date,
                                                                             )
            self.set_table_view(consumption_item)

if __name__ == '__main__':
    app = QApplication([])
    win = ConsumptionList()
    win.search_consumption_information()
    win.show()
    sys.exit(app.exec())
